package top.superflow.utils

import java.io.{File, FileInputStream}
import java.util.Properties

import top.superflow.constant.GlobalConst
import top.superflow.log.Loggable

object PropertyUtil extends Loggable{

  def getProp(url : String) : Option[Properties] = {
    val prop = new Properties()
    try {
      url match {
        case null =>
          logger.error("Can't read properties from url:{}" , url)
        case s if s.startsWith("classpath:") => {
          var classpath = s.replace("classpath:", "")
          if(!classpath.startsWith("/")) classpath = "/" + classpath
          prop.load(getClass.getResourceAsStream(classpath))
        }

        case s : String =>
          if(new File(s).exists()){
            prop.load(new FileInputStream(s))
          }else{
            logger.info("There is no custom properties configured under the superflow home [" +  SuperflowENVUtil + "]")
          }
      }
      return new Some(prop)
    } catch {
      case t: Throwable =>
        logger.error("Error happens when read property at url[{}]",url, t)
    }
    None;
  }

  def getValue(prop : Properties, key:String):Option[String] = {
    try {
      if(prop == null) {
        logger.warn("Properties can't be null")
        return None
      }

      val value = prop.getProperty(key)
      if(value != null){
        return Some(value)
      }
    } catch {
      case t: Throwable => logger.error("Error happens when read property for key:{}", key, t)
    }
    return None;
  }

  def getValue(url:String, key:String):Option[String] = {
    val prop = getProp(url).get
    getValue(prop, key)
  }

  def getSystemProperty(key:String):Option[String] = {
    val positionOfRootProperty = getClass.getResource(GlobalConst.SYSTEM_CONFIG_URI).getFile

    getValue(positionOfRootProperty, key)
  }
}
